package com.kehao.leetcode.hard.array;

import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;

public class FourSumCountSolution {
    //这个自己的思路只能5%？
    public int fourSumCount1(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int result = 0;
        int n = nums1.length;
        HashMap<Integer,Integer> map2 = new HashMap<>();
        int sum = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                sum = nums1[i]+nums2[j];
                if(map2.containsKey(sum)){
                    map2.put(sum,map2.get(sum)+1);
                }else {
                    map2.put(sum,1);
                }
            }
        }
        HashMap<Integer,Integer> map3 = new HashMap<>();
        for (int i = 0; i < n; i++) {
            for(int key : map2.keySet()){
                sum = nums3[i]+key;
                if(map3.containsKey(sum)){
                    map3.put(sum,map3.get(sum)+map2.get(key));
                }else {
                    map3.put(sum,map2.get(key));
                }
            }
        }
        for (int i = 0; i < n; i++) {
            if(map3.containsKey(-nums4[i])){
                result+=map3.get(-nums4[i]);
            }
        }
        return result;
    }

    //官方的思路  无语了还是只有5%  算了
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int result=0;
        int n = nums1.length;
        int sum =0;
        HashMap<Integer,Integer> map12 = new HashMap<>();
        HashMap<Integer,Integer> map34 = new HashMap<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                sum = nums1[i]+nums2[j];
                if(map12.containsKey(sum)){
                    map12.put(sum,map12.get(sum)+1);
                }else {
                    map12.put(sum,1);
                }
                sum = nums3[i]+nums4[j];
                if(map34.containsKey(sum)){
                    map34.put(sum,map34.get(sum)+1);
                }else {
                    map34.put(sum,1);
                }
            }
        }
        for(int k12:map12.keySet()){
            if(map34.containsKey(-k12)){
                result=result+map12.get(k12)*map34.get(-k12);
            }
        }
        return result;
    }


    @Test
    public void test01(){
        int[] nums1 = {1,2}, nums2 = {-2,-1}, nums3 = {-1,2}, nums4 = {0,2};
        int result = fourSumCount(nums1, nums2, nums3, nums4);
        System.out.println(result);
    }
}
